import { types, getParent, Instance, destroy } from "mobx-state-tree";
import { Book } from "./Books";

type BookModel = Instance<typeof Book>;

const CartEntry = types
  .model("CartEntry", {
    quantity: 0,
    book: types.reference(Book),
  })
  .views((self) => ({
    get price() {
      return self.book.price * self.quantity;
    },
  }))
  .actions((self) => ({
    increaseQuantity(number: number) {
      self.quantity += number;
    },
    setQuantity(number: number) {
      if (number < 1) {
        window.alert("数量不能小于1！");
      } else self.quantity = number;
    },
    remove() {
      (getParent(self, 2) as any).remove(self);
    },
  }));

export const CartModel = types
  .model("CartModel", {
    entries: types.array(CartEntry),
  })
  .views((self) => ({
    get subTotal() {
      return self.entries.reduce((sum, e) => sum + e.price, 0);
    },
  }))
  .actions((self) => ({
    addBook(book: BookModel, quantity = 1, notify = true) {
      let entry = self.entries.find((entry) => entry.book === book);
      if (!entry) {
        const c = CartEntry.create({ quantity: 0, book: book as any });
        self.entries.push(c);
        entry = self.entries[self.entries.length - 1];
      }
      entry.increaseQuantity(quantity);
      if (notify) window.alert("添加到购物车成功！");
    },
    remove(book: BookModel) {
      destroy(book);
    },
  }));
